# 定义工具
from langchain.agents import Tool, ConversationalAgent, AgentExecutor
from langchain.chains.llm import LLMChain
from langchain.memory import ConversationBufferMemory
from langchain_core.prompts import MessagesPlaceholder
from langchain_openai import OpenAI

#
llm = OpenAI(
    api_key="sk-VowKQBUMIkSND8WScNJtDLqf3FyqWHQ43LMVUXH1m6GZaopA",
    base_url="https://ai.nengyongai.cn/v1"
)


def search(query):
    return f''


search_tool = Tool(
    name="Search",
    func=search,
    description="用于在互联网上搜索信息的工具。"
)

# 定义记忆组件
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)

# 定义提示模板
prompt = ConversationalAgent.create_prompt(
    [search_tool],
    system_message="你是一个智能助手，可以回答各种问题，必要时可以使用工具。",
    extra_prompt_messages=[MessagesPlaceholder(variable_name="chat_history")]
)


def test():
    #
    llm_chain = LLMChain(llm=llm, prompt=prompt)
    # 代理
    agent = ConversationalAgent(llm_chain=llm_chain)

    # 代理执行器
    agent_executor = AgentExecutor.from_agent_and_tools(
        agent=agent,
        tools=[search_tool],
        memory=memory,
        verbose=True
    )

    # 运行多轮对话
    result1 = agent_executor.run("人工智能的发展历程是怎样的？")
    print(result1)
    result2 = agent_executor.run("有哪些著名的人工智能研究机构？")
    print(result2)
